'use strict';
import React, {Component} from 'react'
import {Link, hashHistory} from 'react-router'
import {HttpService, Tips,imgonError} from '../Tools'
import Header from './Common/Header'
import '../Scss/map.scss'

import imgHead from '../Img/icon/head.png'
import defaultHeadImg from '../Img/icon/defaultHeadImg.png'
import imgClean from '../Img/icon/clean.png'

import imgLbs from '../Img/icon/lbs.png'
import imgGps from '../Img/icon/gps.png'
import imgWifi from '../Img/icon/wifi.png'

import dian from '../Img/icon/dianHead.png'

import imgDian0 from '../Img/icon/dianliang0.png'
import imgDian1 from '../Img/icon/dianliang1.png'
import imgDian2 from '../Img/icon/dianliang2.png'
import imgDian3 from '../Img/icon/dianliang3.png'
import imgDian4 from '../Img/icon/dianliang4.png'

export default class Map extends Component {
    constructor(props) {
        super(props);
        this.babyid = this.props.params.babyid;
        this.babyname = this.props.params.babyname;
        this.map = '';
        this.marker = '';
        this.headimg = '';
        this.state = {
            babyInfo: {
                powerValue:imgDian0,//电量
                datasource:'',//基站类型
                address:'当前设备未定位',
                time:new Date().getHours()+'.'+new Date().getMinutes(),//默认当前时间的小时.分钟
                lat:'39.90923',
                lng:'116.397428',
            }, //学生信息
            locaType: false,//定为动画
        };
    }
    componentWillMount() {
        //获取当前学生的定位信息
        this.getCurrentTrack();
        this.headimg = defaultHeadImg;
        let parHeadimg = this.props.params.headimg;
        if(parHeadimg !='' && parHeadimg != null && parHeadimg != undefined){
            this.headimg = 'media/'+parHeadimg.replace(/\*/g,'/');
        }
    }

    /**
     *  获取定位信息
     */
    getCurrentTrack(){
        HttpService.query({
            url: '/teacherapp/student/getCurrentTrack',
            data: {
                token: localStorage.appToken,
                babyid: this.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10059) {
                    this.init(116.397428, 39.90923);
                    Tips('未获取到定位信息');
                } else if (res.code == 10060) {
                    let datasource = imgLbs,time = '',rct = this;
                    this.init(res.data.lng, res.data.lat);
                    if(res.data.powerValue==1) {
                        datasource = imgGps;
                    }else if(res.data.datasource==2){
                        datasource = imgWifi;
                    }
                    if(res.data.gpstime != null && res.data.gpstime != ''){
                        time = res.data.gpstime.substring(10,16).replace(':','.')
                    }
                    let geocoder = new AMap.Geocoder({radius: 1000, extensions: "all"});
                    geocoder.getAddress([res.data.lng, res.data.lat], function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            rct.state.babyInfo.address = result.regeocode.formattedAddress;
                            rct.setState({babyInfo:rct.state.babyInfo});
                        }
                    });
                    if(!this.state.locaType){
                        this.getCurrentPower();//获取电量
                    }
                    this.state.babyInfo.datasource = datasource;
                    this.state.babyInfo.time = time;
                    this.state.babyInfo.lat = res.data.lat;
                    this.state.babyInfo.lng = res.data.lng;
                    this.setState({babyInfo:this.state.babyInfo,locaType:false});
                    // let getTime = new Date(res.data.gpstime.split(' ')[0]);
                    // let nowTime = new Date();
                    // let tips = getTime.getFullYear() == nowTime.getFullYear() && getTime.getMonth() == nowTime.getMonth() && nowTime.getDate() == getTime.getDate();
                    // if (!tips)
                    //     Tips('无法获取当前定位<br/>将显示上次定位信息')
                } else {
                    Tips(res.data.msg);
                    this.setState({locaType:false});
                }
            })
        });
    }
    /**
     * 获取电量
     */
    getCurrentPower(){
        HttpService.query({
            url: '/teacherapp/student/getCurrentPower',
            data: {
                token: localStorage.appToken,
                babyid: this.babyid,
            },
            success: (res => {
                if(res.code == 10012){
                    let powerValue = imgDian1;
                    if(res.data.powerValue==2){
                        powerValue = imgDian2;
                    }else if(res.data.powerValue==3){
                        powerValue = imgDian3;
                    }else if(res.data.powerValue==4){
                        powerValue = imgDian4;
                    }
                    this.state.babyInfo.powerValue = powerValue;
                    this.setState({babyInfo:this.state.babyInfo});
                } else {
                    Tips(res.msg);
                }

            })
        });
    }

    /**
     * 地图初始化
     * @param lng 纬度
     * @param lat 经度
     */
    init(lng, lat){
        let rct = this;
        if(!rct.state.locaType){
            rct.map = new AMap.Map('container', {
                zoom: 15,
                center: [
                    lng, lat
                ],
                resizeEnable: true
            });
        }else{
            rct.map.clearMap();//清除所有覆盖物
            rct.map.setZoomAndCenter(15, [lng, lat]);//重新定位的时候直接定位中心点
        }
        rct.map.plugin(["AMap.ToolBar"],function(){
            let tool = new AMap.ToolBar({
                position:'RT'
            });
            rct.map.addControl(tool);
        });
        if (lng == 116.397428 && lat == 39.90923) {
            return;
        }

        rct.marker = new AMap.Marker({
            map: rct.map,
            position: [lng, lat],
            content:'<img src='+dian+' class="headBgImg" />',

        });
        rct.marker.setMap(rct.map);
        rct.marker = new AMap.Marker({
            map: rct.map,
            position: [lng, lat],
            content:'<img src='+this.headimg+' class="headImg" />',
        });
        rct.marker.setMap(rct.map);

        let circle = new AMap.Circle({
            center: new AMap.LngLat(lng, lat), // 圆心位置
            radius: 100, //半径
            strokeColor: "#00b4ed", //线颜色
            strokeOpacity: 1, //线透明度
            fillColor: "#00b4ed", //填充颜色
            strokeWeight: 1, //线宽
            fillOpacity: 0.2 //填充透明度
        });
        circle.setMap(rct.map);

    }

    /**
     * 点击定位
     * @returns {XML}
     */
    location(){
        if(!this.state.locaType){
            this.setState({locaType:true});
            this.getCurrentTrack();//重新获取定为信息
        }
    }

    /**
     * 返回到列表页面
     * @returns {XML}
     */
    goBack(){
        hashHistory.goBack(-1);
    }

    /**
     * 显示默认图片
     * @param e
     */
    mapImgonError(e){
        let rct = this;
        document.querySelector('.h_back').src = defaultHeadImg;
        if(document.querySelector('.headImg')){
            document.querySelector('.headImg').src = defaultHeadImg;
        }else{
            setTimeout(function () {
                rct.mapImgonError();
            },200);
        }
    }
    render() {

        return (
            <div className='map'>
                <Header back={<img className='h_back' src={this.headimg} onError={this.mapImgonError.bind(this)} />} link={<img onClick={this.goBack.bind(this)} className='h_link' src={imgClean}/>}>
                    <div className='info'>
                        <div className="title">
                            <span className="name">{this.babyname}</span>
                            <span className="position">[最后上报位置]</span>
                            <img src={this.state.babyInfo.powerValue}/>
                            {
                                this.state.babyInfo.datasource!=''?<img src={this.state.babyInfo.datasource} />:''
                            }
                        </div>
                        <div className="content">
                            <span className="time">{this.state.babyInfo.time}</span>
                            <span className="address">{this.state.babyInfo.address}</span>
                        </div>
                    </div>
                </Header>
                <div className="location" onClick={this.location.bind(this)}>
                    <div className={this.state.locaType==false?'locationBg':'locationBg ing'}/>
                    {this.state.locaType==false?'':<div className="locationLoading"/>}
                </div>
                <div id="container"></div>
            </div>
        )
    }
}
